﻿using IOP.Orleans.MessageHub;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Test.Shared;
using Newtonsoft.Json;

namespace SimpleObserverClient
{
    public class ObserverHostService : IHostedService
    {
        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<ObserverHostService> _Logger;
        /// <summary>
        /// 消息服务
        /// </summary>
        private readonly IMessageHubService _MessageHubService;
        /// <summary>
        /// 控制器
        /// </summary>
        private AutoResetEvent AutoResetEvent = new AutoResetEvent(false);

        public ObserverHostService(ILogger<ObserverHostService> logger, IMessageHubService hubService)
        {
            _Logger = logger;
            _MessageHubService = hubService;
        }

        public Task StartAsync(CancellationToken cancellationToken)
        {
            StartObserver(cancellationToken);
            return Task.CompletedTask;
        }

        public Task StopAsync(CancellationToken cancellationToken)
        {
            AutoResetEvent.Set();
            return Task.CompletedTask;
        }

        private void StartObserver(CancellationToken cancellationToken)
        {
            Task.Factory.StartNew(async () =>
            {
                var ob = await _MessageHubService.RegistObserver<byte[]>((msg) =>
                {
                    string m = Encoding.UTF8.GetString(msg);
                    var data = JsonConvert.DeserializeObject<TestMessage>(m);
                    _Logger.LogInformation($"Receive message: {data.B}");
                    AutoResetEvent.Set();
                    return Task.CompletedTask;
                }, "Hello");
                ob.OnObserverBeginListened += Ob_OnObserverBeginListened;
                ob.OnObserverAbortListened += Ob_OnObserverAbortListened;
                await Task.Factory.StartNew(() =>
                {
                    while (!cancellationToken.IsCancellationRequested)
                    {
                        AutoResetEvent.WaitOne();
                    }
                }, cancellationToken);
            });
        }

        private Task Ob_OnObserverAbortListened(IMessageDispatcher obj)
        {
            _Logger.LogWarning($"{obj.Name} has abort listen");
            return Task.CompletedTask;
        }

        private Task Ob_OnObserverBeginListened(IMessageDispatcher obj)
        {
            _Logger.LogInformation($"{obj.Name} has begin listen");
            return Task.CompletedTask;
        }
    }
}
